// import Vue from 'vue'
import router from './router'
import store from './store'
import { Notification } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/login/transferStation']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  console.log('to', to)
  console.log('from', from)
  const token = localStorage.getItem('TOKEN')
  console.log('token', token)
  // next()
  // return
  if (token) {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      const routes = store.getters.addRoutes || []
      console.log('routes', routes)
      console.log('routes.length', routes.length)
      if (routes.length > 0) {
        console.log('1')
        next()
      } else {
        console.log('2')
        // const accessRoutes = await store.dispatch('permission/getPermissionMenu')
        // console.log('accessRoutes', accessRoutes)
        // router.addRoutes(accessRoutes)
        // next()
        // return
        try {
          // 这个是给sidebar组件赋值
          const accessRoutes = await store.dispatch('permission/getPermissionMenu')
          router.addRoutes(accessRoutes)
          console.log('accessRoutes', accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          localStorage.removeItem('TOKEN')
          store.commit('permission/CLEAR_ROUTES') // 清空路由
          Notification.error({
            title: error || '系统异常，请重新登录',
            duration: 5000
          })
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
